package jrain.flow.engine.fi;

import jrain.flow.engine.bean.FlowDef;
import jrain.flow.engine.bean.FlowInstance;
import jrain.flow.engine.bean.NodeDef;
import jrain.flow.engine.bean.NodeInstance;
import jrain.flow.engine.uitls.FlowUtils;
import jrain.utils.exception.BusinessException;
import jrain.utils.lang.StringUtils;

public class PIServiceImpl implements FiService {

	@Override
	public void startFlow(FlowInstance flowInstance) {
		if (StringUtils.isEmpty(flowInstance.getOldFiId())) {

		}
		String flowCode = StringUtils.trimNull(flowInstance.getFlowCode());
		int flowVersion = flowInstance.getVersion();
		if (flowCode.length() == 0) {
			throw new BusinessException("flowCode is empty!");
		}
		FlowDef flowDef = FlowUtils.getFlowCache().getPdByCodeAndVersion(flowCode, flowVersion);
		if (flowDef == null) {
			throw new BusinessException("flowDef is empty!");
		}
		String startCode = StringUtils.trimNull(flowInstance.getStartCode());
		NodeDef startNode = null;
		if (startCode.length() > 0) {
			startNode = flowDef.getNode(startCode);
		} else {
			startNode = flowDef.getStartNode();
		}
		if (startNode == null) {
			throw new BusinessException("StartNode is empty!");
		}
		// 启动流程
		NodeInstance nodeInstance = new NodeInstance();
		nodeInstance.setNodeDef(startNode);
		FlowUtils.getDispatchService().doNode(nodeInstance);
	}

}
